﻿using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace MvcStarterKit.UI.Helpers
{
	public class WindsorBootstrapper
	{
		public static IWindsorContainer Container { get; set; }

		public static void Initialize()
		{
			Container = new WindsorContainer();

			RegisterControllers();

			RegisterDefaultServices();
		}

		private static void RegisterControllers()
		{
			Container.Register(AllTypes.Of<IController>()
				.FromAssembly(Assembly.GetExecutingAssembly())
				.Configure(
					cfg => cfg.LifeStyle.Is(LifestyleType.Transient)
				));
		}

		private static void RegisterDefaultServices()
		{
			ServiceDescriptor.ServiceSelector firstNonGenericInterface =
					 delegate(Type type, Type baseType)
					 {
						 var interfaces = type.GetInterfaces()
								 .Where(
										 i => i.IsGenericType == false
								 );

						 if (interfaces.Count() > 0)
						 {
							 return new[] { interfaces.ElementAt(0) };
						 }
						 return null;
					 };

			Container.Register(AllTypes.Pick()
			                   	.FromAssemblyNamed("MvcStarterKit.Infrastructure")
			                   	.If(t => t.GetInterfaces().Count() > 0)
													.WithService.Select(firstNonGenericInterface));
		}


	}
}